<script setup lang="ts">
import type { Resource } from '#/api/resource-center/types';

import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message, Modal } from 'ant-design-vue';

import { resourceApi } from '#/api/resource-center/resource-api';
import {
  ResourceStatus,
  ResourceType,
  SystemStatus,
} from '#/api/resource-center/types';

import ResourceDetail from './components/ResourceDetail.vue';

// ==================== 响应式数据 ====================

const loading = ref(false);
const resourceList = ref<Resource[]>([]);
const selectedTreeKeys = ref<string[]>([]);
const expandedTreeKeys = ref<string[]>([]);
const searchKeyword = ref('');
const filterType = ref<ResourceType>();
const filterStatus = ref<SystemStatus>();
const createModalVisible = ref(false);
const detailDrawerVisible = ref(false);
const selectedResource = ref<null | Resource>(null);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 创建表单
const createForm = reactive({
  name: '',
  code: '',
  type: ResourceType.CAPABILITY,
  systemStatus: SystemStatus.DRAFT,
  description: '',
  labelsInput: '',
  labels: {} as Record<string, string>,
});

// ==================== 计算属性 ====================

// 资源类型选项
const resourceTypes = computed(() => [
  { value: ResourceType.DIGITAL, label: '数字资源', icon: 'FileTextOutlined' },
  { value: ResourceType.HUMAN, label: '人力资源', icon: 'UserOutlined' },
  { value: ResourceType.PHYSICAL, label: '物理资源', icon: 'ToolOutlined' },
  { value: ResourceType.SERVICE, label: '服务资源', icon: 'ApiOutlined' },
  { value: ResourceType.VIRTUAL, label: '虚拟资源', icon: 'CloudOutlined' },
  {
    value: ResourceType.CAPABILITY,
    label: '能力资源',
    icon: 'ant-design:thunderbolt-outlined',
  },
]);

// 系统状态选项
const systemStatuses = computed(() => [
  { value: SystemStatus.DRAFT, label: '草稿', color: 'default' },
  { value: SystemStatus.PUBLISHED, label: '已发布', color: 'blue' },
  { value: SystemStatus.ACTIVE, label: '运行中', color: 'green' },
  { value: SystemStatus.INACTIVE, label: '已下线', color: 'orange' },
  { value: SystemStatus.DEPRECATED, label: '已废弃', color: 'red' },
  { value: SystemStatus.RETIRED, label: '已退役', color: 'gray' },
]);

// 资源树数据
const resourceTreeData = computed(() => [
  {
    key: 'all',
    title: '全部资源',
    icon: 'AppstoreOutlined',
    color: '#1890ff',
    count: resourceList.value.length,
  },
  {
    key: 'capability',
    title: '能力资源',
    icon: 'ant-design:thunderbolt-outlined',
    color: '#52c41a',
    count: resourceList.value.filter((r) => r.type === ResourceType.CAPABILITY)
      .length,
  },
  {
    key: 'physical',
    title: '物理资源',
    icon: 'ToolOutlined',
    color: '#fa8c16',
    count: resourceList.value.filter((r) => r.type === ResourceType.PHYSICAL)
      .length,
  },
  {
    key: 'service',
    title: '服务资源',
    icon: 'ApiOutlined',
    color: '#722ed1',
    count: resourceList.value.filter((r) => r.type === ResourceType.SERVICE)
      .length,
  },
  {
    key: 'digital',
    title: '数字资源',
    icon: 'FileTextOutlined',
    color: '#13c2c2',
    count: resourceList.value.filter((r) => r.type === ResourceType.DIGITAL)
      .length,
  },
]);

// 表格列定义
const resourceColumns = [
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '资源类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '系统状态',
    dataIndex: 'systemStatus',
    key: 'systemStatus',
    width: 120,
  },
  {
    title: '版本',
    dataIndex: 'version',
    key: 'version',
    width: 100,
  },
  {
    title: '标签',
    dataIndex: 'labels',
    key: 'labels',
    width: 200,
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 表单验证规则
const createRules = {
  name: [{ required: true, message: '请输入资源名称' }],
  code: [{ required: true, message: '请输入资源代码' }],
  type: [{ required: true, message: '请选择资源类型' }],
  systemStatus: [{ required: true, message: '请选择系统状态' }],
};

// ==================== 方法 ====================

// 加载资源列表
const loadResources = async () => {
  loading.value = true;
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value,
      type: filterType.value,
      status: filterStatus.value
        ? (filterStatus.value as unknown as ResourceStatus)
        : undefined,
    };

    const response = await resourceApi.search(params);
    resourceList.value = response.list as unknown as Resource[];
    pagination.total = response.total;
  } catch (error) {
    message.error('加载资源列表失败');
    console.error('Load resources error:', error);
  } finally {
    loading.value = false;
  }
};

// 刷新资源
const refreshResources = () => {
  loadResources();
};

// 搜索
const onSearch = () => {
  pagination.current = 1;
  loadResources();
};

// 筛选变化
const onFilterChange = () => {
  pagination.current = 1;
  loadResources();
};

// 表格变化
const onTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadResources();
};

// 树选择
const onTreeSelect = (keys: string[]) => {
  selectedTreeKeys.value = keys;
  if (keys.length > 0 && keys[0] !== 'all') {
    const type = keys[0] as ResourceType;
    filterType.value = type;
    onFilterChange();
  } else {
    filterType.value = undefined;
    onFilterChange();
  }
};

// 显示创建模态框
const showCreateModal = () => {
  createModalVisible.value = true;
};

// 创建资源
const createResource = async () => {
  try {
    const resourceData = {
      ...createForm,
      tenantId: 'default', // 这里应该从用户上下文获取
      version: 'v1.0.0',
      facets: {
        attributes: { bags: [] },
        lifecycle: {
          machine: { states: ['DRAFT'], initial: 'DRAFT', transitions: [] },
          currentState: 'DRAFT',
        },
        behaviors: { definitions: [] },
        events: { publish: [], subscribe: [] },
        relations: { edges: [] },
        versions: { history: [] },
        monitoring: { metrics: [], alerts: [] },
      },
      governance: {
        visibility: 'PRIVATE' as const,
        owners: [],
      },
    };

    await resourceApi.create(resourceData);
    message.success('资源创建成功');
    createModalVisible.value = false;
    resetCreateForm();
    loadResources();
  } catch (error) {
    message.error('资源创建失败');
    console.error('Create resource error:', error);
  }
};

// 取消创建
const cancelCreate = () => {
  createModalVisible.value = false;
  resetCreateForm();
};

// 重置创建表单
const resetCreateForm = () => {
  Object.assign(createForm, {
    name: '',
    code: '',
    type: ResourceType.CAPABILITY,
    systemStatus: SystemStatus.DRAFT,
    description: '',
    labelsInput: '',
    labels: {},
  });
};

// 解析标签
const parseLabels = () => {
  const labels: Record<string, string> = {};
  if (createForm.labelsInput) {
    createForm.labelsInput.split(',').forEach((item) => {
      const [key, value] = item.trim().split(':');
      if (key && value) {
        labels[key.trim()] = value.trim();
      }
    });
  }
  createForm.labels = labels;
};

// 查看资源
const viewResource = (resource: Resource) => {
  selectedResource.value = resource;
  detailDrawerVisible.value = true;
};

// 编辑资源
const editResource = (resource: Resource) => {
  selectedResource.value = resource;
  detailDrawerVisible.value = true;
};

// 发布资源
const publishResource = async (resource: Resource) => {
  try {
    await resourceApi.publish(resource.id);
    message.success('资源发布成功');
    loadResources();
  } catch (error) {
    message.error('资源发布失败');
    console.error('Publish resource error:', error);
  }
};

// 显示版本历史
const showVersions = async (resource: Resource) => {
  try {
    const versions = await resourceApi.getVersions(resource.id);
    // 这里可以打开版本历史模态框
    console.log('Resource versions:', versions);
  } catch (error) {
    message.error('获取版本历史失败');
    console.error('Get versions error:', error);
  }
};

// 显示关系图
const showGraph = async (resource: Resource) => {
  try {
    const graph = await resourceApi.getGraph(resource.id);
    // 这里可以打开关系图模态框
    console.log('Resource graph:', graph);
  } catch (error) {
    message.error('获取关系图失败');
    console.error('Get graph error:', error);
  }
};

// 删除资源
const deleteResource = (resource: Resource) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除资源 "${resource.name}" 吗？`,
    onOk: async () => {
      try {
        await resourceApi.delete(resource.id);
        message.success('资源删除成功');
        loadResources();
      } catch (error) {
        message.error('资源删除失败');
        console.error('Delete resource error:', error);
      }
    },
  });
};

// 资源更新回调
const onResourceUpdate = () => {
  loadResources();
};

// 获取资源类型颜色
const getResourceTypeColor = (type: ResourceType) => {
  const typeMap: Record<ResourceType, string> = {
    [ResourceType.DIGITAL]: 'cyan',
    [ResourceType.HUMAN]: 'blue',
    [ResourceType.PHYSICAL]: 'orange',
    [ResourceType.SERVICE]: 'purple',
    [ResourceType.VIRTUAL]: 'geekblue',
    [ResourceType.CAPABILITY]: 'green',
  };
  return typeMap[type] || 'default';
};

// 获取资源类型标签
const getResourceTypeLabel = (type: ResourceType) => {
  const typeOption = resourceTypes.value.find((t) => t.value === type);
  return typeOption?.label || type;
};

// 获取状态颜色
const getStatusColor = (status: SystemStatus) => {
  const statusOption = systemStatuses.value.find((s) => s.value === status);
  return statusOption?.color || 'default';
};

// 获取状态标签
const getStatusLabel = (status: SystemStatus) => {
  const statusOption = systemStatuses.value.find((s) => s.value === status);
  return statusOption?.label || status;
};

// ==================== 生命周期 ====================

onMounted(() => {
  loadResources();
});
</script>

<template>
  <div class="resource-factory">
    <!-- 顶部工具栏 -->
    <div class="factory-header">
      <div class="header-left">
        <h2>资源工厂</h2>
        <a-tag color="blue">统一资源管理</a-tag>
      </div>
      <div class="header-right">
        <a-button type="primary" @click="showCreateModal">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          新建资源
        </a-button>
        <a-button @click="refreshResources">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="factory-content">
      <!-- 左侧资源树 -->
      <div class="resource-tree">
        <a-tree
          v-model:selected-keys="selectedTreeKeys"
          v-model:expanded-keys="expandedTreeKeys"
          :tree-data="resourceTreeData"
          :field-names="{ title: 'title', key: 'key', children: 'children' }"
          @select="onTreeSelect"
        >
          <template #title="{ title, data }">
            <div class="tree-node">
              <span class="node-icon" :style="{ color: data?.color }">
                <component :is="data?.icon" />
              </span>
              <span class="node-title">{{ title }}</span>
              <span v-if="data?.count" class="node-count">({{ data.count }})</span>
            </div>
          </template>
        </a-tree>
      </div>

      <!-- 右侧资源列表 -->
      <div class="resource-list">
        <!-- 搜索和筛选 -->
        <div class="list-header">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索资源名称、代码或标签"
            style="width: 300px"
            @search="onSearch"
          />
          <div class="filters">
            <a-select
              v-model:value="filterType"
              placeholder="资源类型"
              style="width: 150px"
              allow-clear
              @change="onFilterChange"
            >
              <a-select-option
                v-for="type in resourceTypes"
                :key="type.value"
                :value="type.value"
              >
                {{ type.label }}
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="filterStatus"
              placeholder="系统状态"
              style="width: 150px"
              allow-clear
              @change="onFilterChange"
            >
              <a-select-option
                v-for="status in systemStatuses"
                :key="status.value"
                :value="status.value"
              >
                {{ status.label }}
              </a-select-option>
            </a-select>
          </div>
        </div>

        <!-- 资源表格 -->
        <a-table
          :columns="resourceColumns"
          :data-source="resourceList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="onTableChange"
        >
          <!-- 资源类型列 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'type'">
              <a-tag :color="getResourceTypeColor(record.type)">
                {{ getResourceTypeLabel(record.type) }}
              </a-tag>
            </template>

            <!-- 系统状态列 -->
            <template v-else-if="column.key === 'systemStatus'">
              <a-tag :color="getStatusColor(record.systemStatus)">
                {{ getStatusLabel(record.systemStatus) }}
              </a-tag>
            </template>

            <!-- 版本列 -->
            <template v-else-if="column.key === 'version'">
              <a-tag color="blue">{{ record.version }}</a-tag>
            </template>

            <!-- 标签列 -->
            <template v-else-if="column.key === 'labels'">
              <div class="labels-container">
                <a-tag
                  v-for="(value, key) in record.labels"
                  :key="key"
                  size="small"
                >
                  {{ key }}: {{ value }}
                </a-tag>
              </div>
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button
                  type="link"
                  size="small"
                  @click="viewResource(record)"
                >
                  查看
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  @click="editResource(record)"
                >
                  编辑
                </a-button>
                <a-dropdown>
                  <a-button type="link" size="small">
                    更多
                    <DownOutlined />
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="publishResource(record)">
                        <template #icon>
                          <IconifyIcon icon="ant-design:rocket-outlined" />
                        </template>
                        发布
                      </a-menu-item>
                      <a-menu-item @click="showVersions(record)">
                        <template #icon>
                          <HistoryOutlined />
                        </template>
                        版本历史
                      </a-menu-item>
                      <a-menu-item @click="showGraph(record)">
                        <template #icon>
                          <IconifyIcon icon="ant-design:share-alt-outlined" />
                        </template>
                        关系图
                      </a-menu-item>
                      <a-menu-divider />
                      <a-menu-item danger @click="deleteResource(record)">
                        <template #icon>
                          <IconifyIcon icon="ant-design:delete-outlined" />
                        </template>
                        删除
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 新建资源模态框 -->
    <a-modal
      v-model:open="createModalVisible"
      title="新建资源"
      width="800px"
      @ok="createResource"
      @cancel="cancelCreate"
    >
      <a-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="资源名称" name="name">
              <a-input
                v-model:value="createForm.name"
                placeholder="请输入资源名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="资源代码" name="code">
              <a-input
                v-model:value="createForm.code"
                placeholder="请输入资源代码"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="资源类型" name="type">
              <a-select
                v-model:value="createForm.type"
                placeholder="请选择资源类型"
              >
                <a-select-option
                  v-for="type in resourceTypes"
                  :key="type.value"
                  :value="type.value"
                >
                  {{ type.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="系统状态" name="systemStatus">
              <a-select
                v-model:value="createForm.systemStatus"
                placeholder="请选择系统状态"
              >
                <a-select-option
                  v-for="status in systemStatuses"
                  :key="status.value"
                  :value="status.value"
                >
                  {{ status.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="createForm.description"
            placeholder="请输入资源描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="标签" name="labels">
          <a-input
            v-model:value="createForm.labelsInput"
            placeholder="请输入标签，格式：key1:value1,key2:value2"
            @change="parseLabels"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 资源详情抽屉 -->
    <a-drawer
      v-model:open="detailDrawerVisible"
      title="资源详情"
      width="800px"
      placement="right"
    >
      <ResourceDetail
        v-if="selectedResource"
        :resource="selectedResource"
        @update="onResourceUpdate"
      />
    </a-drawer>
  </div>
</template>

<style lang="less" scoped>
.resource-factory {
  height: 100%;
  display: flex;
  flex-direction: column;

  .factory-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
      }
    }

    .header-right {
      display: flex;
      gap: 8px;
    }
  }

  .factory-content {
    flex: 1;
    display: flex;
    overflow: hidden;

    .resource-tree {
      width: 280px;
      border-right: 1px solid #f0f0f0;
      background: #fff;
      padding: 16px;

      .tree-node {
        display: flex;
        align-items: center;
        gap: 8px;

        .node-icon {
          font-size: 16px;
        }

        .node-title {
          flex: 1;
        }

        .node-count {
          color: #999;
          font-size: 12px;
        }
      }
    }

    .resource-list {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: #fff;

      .list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 24px;
        border-bottom: 1px solid #f0f0f0;

        .filters {
          display: flex;
          gap: 12px;
        }
      }

      .labels-container {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
      }
    }
  }
}
</style>
